﻿using System;
using System.Windows;
using System.Windows.Browser;
using System.Collections.Generic;
using System.Globalization;

namespace SBPweb.PROvibe.Business.Client.Library.Context
{

    public class CookieHandler
    {

        public static bool Contains(string key)
        {
            Dictionary<string, string> cookies = GetCookieBag();
            return cookies.ContainsKey(key);
        }

        public static void Put<T>(string key, T value)
        {
            Put<T>(key, value, DateTime.MaxValue);
        }

        public static void Put<T>(string key, T value, DateTime expires)
        {
            string newCookie = key + "=" + value + ";expires=" + expires.ToString("R");
            HtmlPage.Document.SetProperty("cookie", newCookie);
        }

        public static T Get<T>(string key)
        {
            Dictionary<string, string> cookies = GetCookieBag();
            if (!cookies.ContainsKey(key))
            {
                return default(T);
            }
            //foreach (string cookie in cookies)
            //{
            //    string[] keyValue = cookie.Split('=');
            //    if (keyValue.Length == 2)
            //    {
            //        if (keyValue[0].ToString() == key)
            //        {
            //            return (T)Convert.ChangeType(keyValue[1], typeof(T), CultureInfo.CurrentUICulture);
            //        }
            //    }
            //}
            return (T)Convert.ChangeType(cookies[key], typeof(T), CultureInfo.CurrentUICulture);
        }

        private static Dictionary<string, string> GetCookieBag()
        {
            Dictionary<string, string> cookies = new Dictionary<string, string>();
            string[] split = HtmlPage.Document.Cookies.Split(';');
            if (split.Length < 1)
            {
                return cookies;
            }
            foreach (string cookie in split)
            {
                string[] keyValue = cookie.Split('=');
                if (keyValue.Length > 1)
                {
                    cookies.Add(keyValue[0].Trim(), keyValue[1].Trim());
                }
            }
            return cookies;
        }

    }

}